<div class="row user_control">
	<div class="col-lg-12">
		<div class="input-group">
			<span class="input-group-btn">
				<button class="btn btn-default search_button" type="button" id="search">Поиск!</button>
			</span>
			<input type="text" class="form-control" placeholder="e-mail..." id="search_input" value="<?= (isset($sw) ? $sw : '') ?>">
			<span class="input-group-btn">
			<button type="button" class="btn btn-primary" id="create_user_btn">Создать</button> 
			</span> 
		</div><!-- /input-group -->
	</div>
</div><!-- /.row -->
<div class="row">
  <div class="col-lg-12">
    <div class="table-responsive">
        <table class="table table-hover table-striped tablesorter">
            <thead>
                <tr>
                    <th class="header">
                        id
                    </th>
                    <th class="header">
                        E-Mail
                    </th>
                    <th class="header">
                        Дата регистрации
                    </th>
                    <th class="header">
                        Активный
                    </th>
                    <th class="header">
                        Статус
                    </th>
                    <th class="header">
                        Группа
                    </th>
                    <th class="header">
                        Последний вход
                    </th>
                    <th class="header">
                        Действия
                    </th>
                </tr>
            </thead>
            <tbody>
                <? foreach($users as $user): ?>
                    <tr id="<?= $user->id ?>" class="user-row">
                        <td><?= $user->id ?></td>
                        <td class="user_email" id="<?= $user->id ?>"><?= $user->email ?></td>
                        <td><?= $user->reg_date . ' ' . $user->reg_time ?></td>
                        <td>
                            
                            <select name="active" id="<?= $user->id ?>" class="dropdown-active" disabled>
                                <option <?= ($user->active == "Y") ? 'selected="selected"' : '' ?>  value="Y">Да</option>
                                <option <?= ($user->active == "N") ? 'selected="selected"' : '' ?> value="N">Нет</option>
                            </select>
                        </td>
                        <td><?= $user->status ?></td>
                        <td>

                            <select name="group" id="<?= $user->id ?>" class="dropdown-group" disabled>
                                <? foreach($groups as $group): ?>
                                    <option <?= ($user->group == $group->id) ? 'selected="selected"' : '' ?>  value="<?=$group->id?>"><?= $group->group_name ?></option>
                                <? endforeach ?>
                            </select>
                        </td>
                        <td><?= ($user->last_login == '') ? "<i>Нет</i>" : $user->last_login ?></td>
                        <td>
                        <a href="#" id="<?= $user->id ?>" class="user-change">Изменить</a>
                        <a href="#" id="<?= $user->id ?>" class="user-delete" style="display: none;">Удалить</a>                 
                    
                        </td>
                    </tr>
                <? endforeach ?>
            </tbody>
        </table>
        </div>
    </div>
</div><!-- /.row -->
<div class="row">
	<div class="col-lg-4">
		<div class="bs-example">
			<ul class="pagination pagination-sm">
				<li class="disabled"><a href="#">&laquo;</a></li>
				<li class="active"><a href="#">1</a></li>
				<li><a href="#">2</a></li>
				<li><a href="#">3</a></li>
				<li><a href="#">4</a></li>
				<li><a href="#">5</a></li>
				<li><a href="#">&raquo;</a></li>
			</ul>
		</div>
	</div>
</div><!-- /.row -->

<!-- Modal delete-->
<div class="modal fade" id="modal_delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Удаление пользователя</h4>
      </div>
      <div class="modal-body">
         <div id="modal_text">
         	<div class="row">
			 	<div class="col-lg-12">
				 	<p id="user_information_delete"></p>
				 	<h5><b>Внимание!</b> Данное действие нельзя будет отменить!</h5> 
				 	<div class="progress progress-striped active" id="modal_progress_delete" style="display: none;">
					 	<div class="progress-bar"  role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-    valuemax="100" style="width: 100%">
					 	</div>
					</div>
				</div>
			</div>
		</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="ok_delete_user">Удалить</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
      </div>
    </div>
  </div>
</div><!-- /.modal -->

<!-- Modal change status-->
<div class="modal fade" id="modal_change_status" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Изменение статуса пользователя</h4>
      </div>
      <div class="modal-body">
         <div id="modal_text">
         	<div class="row">
			 	<div class="col-lg-12">
				 	<p id="user_information_change_status"></p>
				 	<div class="progress progress-striped active" id="modal_progress_change_status" style="display: none;">
					 	<div class="progress-bar"  role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-    valuemax="100" style="width: 100%">
					 	</div>
					 </div>
				</div>
			</div>
		</div>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="ok_change_status">Применить</button>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="no_change_status">Отмена</button>
      </div>
    </div>
  </div>
</div><!-- /.modal -->

<!-- Modal change group-->
<div class="modal fade" id="modal_change_group" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Изменение группы пользователя</h4>
      </div>
      <div class="modal-body">
         <div id="modal_text">
         	<div class="row">
			 	<div class="col-lg-12">
				 	<p id="user_information_change_group"></p>
				 	<div class="progress progress-striped active" id="modal_progress_change_group" style="display: none;">
					 	<div class="progress-bar"  role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-    valuemax="100" style="width: 100%">
					 	</div>
					</div>
				</div>
			</div>
		</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="ok_change_group">Применить</button>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="no_change_group">Отмена</button>
      </div>
    </div>
  </div>
</div><!-- /.modal -->

<!-- Modal create new user-->
<div class="modal fade" id="create_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Создать нового пользователя</h4>
      </div>
      <div class="modal-body">
         <div id="modal_text">
         	<div class="row">
			 	<div class="col-lg-12">
				 	 <div class="alert alert-danger" id="error_alert" style="display: none">
                      <p id="error_text">Тут вставляем ошибку</p>
					 </div>
					 <div class="alert alert-dismissable alert-success" id="success_alert" style="display: none">
						 <p id="success_text">Тут вставляем успех</p>
					</div>
				 	<div class="form-group user_form" id="email_form_group">
					 	<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
					 	<div class="col-sm-10">
						 	<input type="email" class="form-control" id="inputEmail" placeholder="Email">
						 </div>
					</div>
					<div class="form-group user_form" id="pass_form_group">
						<label for="inputPassword3" class="col-sm-2 control-label">Пароль</label>
						<div class="col-sm-10">
							<input type="text" class="form-control" id="inputPassword" placeholder="Пароль">
							<div class="checkbox">
								<label>
									<input type="checkbox" id="notify"> Отправить уведомление
								</label>
							</div>
							<a href="#" class="generate_pass" id="generate_pass">Сгенерировать пароль</a>
						</div>
					</div>
				</div>
			</div>
         </div>
	</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="ok_create_user">Создать</button>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="no_create_user">Закрыть</button>
      </div>
    </div>
  </div>
</div><!-- /.modal -->                


              

                



<script type="text/javascript">
        $(function(){
        //click enable selector and show delete button by id
        $(".user-change").click(function(){
            var id = $(this).attr('id');
            $("select").prop( "disabled", true );
            $("tr.user-row").css("color","#333333");
            $("a.user-delete").hide();
            $("a.user-change").show();
            $("tr.user-row[id='"+id+"']").css("color","#428bca");
            $("select.dropdown-active[id='"+id+"']").prop('disabled', false);
            $("select.dropdown-group[id='"+id+"']").prop('disabled', false);
            $(".user-change[id='"+id+"']").hide();
            $("a.user-delete[id='"+id+"']").show();
            return false;
        });
         // end click
  
        //delete user
        $(".user-delete").click(function(){
            var id = $(this).attr('id');
            var user_email = $("td.user_email[id='"+id+"']").text();
            $( "p#user_information_delete" ).html( "Вы уверены, что хотите удалить пользователя <b>"+user_email+"</b>?");
            $("#modal_delete").modal("show");
            $(document).off('click', '#ok_delete_user').on('click', '#ok_delete_user', function(){
                $("#modal_progress_delete").show();
                $.post('<?= $this->config->site_url('ajax/deleteUser') ?>', {'userId': id});
                $("#modal_progress_delete").hide();
                $("#modal_delete").modal("hide");
                $("tr.user-row[id='"+id+"']").hide("slow");
                });
         });       
       //end delete user

        //change user status
        $("select.dropdown-active").focus(function(){
        	var id = $(this).attr('id');
			var val_selected_old = $(this).val();
        	$("select.dropdown-active[id='"+id+"']").change(function(){
				var val = "";
				var text = "";
					$("select.dropdown-active[id='"+id+"'] option:selected").each(function () {
                		val += $(this).val();
					});
				text = getValText(val);
				var user_email = $("td.user_email[id='"+id+"']").text();
				$( "p#user_information_change_status").html( "Вы уверены, что хотите изменить статус пользователя <b>"+user_email+"</b>?");
				$("#modal_change_status").modal("show");
				//Ok button click
				$(document).off('click', '#ok_change_status').on('click', '#ok_change_status', function(){
					$("#modal_progress_change_status").show();
				    $.post('<?= $this->config->site_url('ajax/setUserActive') ?>', {'userId': id, 'val': val});
				    $("select.dropdown-active[id='"+id+"']").blur();
				    $("select.dropdown-active[id='"+id+"']").prop('disabled', true);
                    $("select.dropdown-group[id='"+id+"']").prop('disabled', true);
				    $("a.user-delete[id='"+id+"']").hide();
                    $(".user-change[id='"+id+"']").show();
                    $("tr.user-row[id='"+id+"']").css("color","#333333");
				    $("#modal_progress_change_status").hide();
				    $("#modal_change_status").modal("hide");
				});
				//Dismiss button click
				$("#no_change_status").click(function(){
					$("select.dropdown-active[id='"+id+"']").val(val_selected_old);
					$("select.dropdown-active[id='"+id+"']").blur();
					$("select.dropdown-active[id='"+id+"']").prop('disabled', true);
                    $("select.dropdown-group[id='"+id+"']").prop('disabled', true);
				    $("a.user-delete[id='"+id+"']").hide();
                    $(".user-change[id='"+id+"']").show();
                    $("tr.user-row[id='"+id+"']").css("color","#333333");
					$("#modal_change_status").modal("hide");
				});

			});

        });
        //end change user status
        
        //change user group
        $("select.dropdown-group").focus(function(){
        	var id = $(this).attr('id');
			var val_selected_old = $(this).val();
        	$("select.dropdown-group[id='"+id+"']").change(function(){
				var val = "";
				var text = "";
					$("select.dropdown-group[id='"+id+"'] option:selected").each(function () {
                		val += $(this).val();
					});
				text = getValText(val);
				var user_email = $("td.user_email[id='"+id+"']").text();
				$( "p#user_information_change_group").html( "Вы уверены, что хотите изменить группу пользователя <b>"+user_email+"</b> на <b>"+text+"</b>?");
				$("#modal_change_group").modal("show");
				//Ok button click
				$(document).off('click', '#ok_change_group').on('click', '#ok_change_group', function(){
					$("#modal_progress_change_group").show();
				    $.post('/ajax/setUserGroup', {'userId': id, 'val': val});
				    $("select.dropdown-group[id='"+id+"']").blur();
				    $("select.dropdown-active[id='"+id+"']").prop('disabled', true);
                    $("select.dropdown-group[id='"+id+"']").prop('disabled', true);
				    $("a.user-delete[id='"+id+"']").hide();
                    $(".user-change[id='"+id+"']").show();
                    $("tr.user-row[id='"+id+"']").css("color","#333333");
				    $("#modal_progress_change_group").hide();
				    $("#modal_change_group").modal("hide");
				});
				//Dismiss button click
				$("#no_change_group").click(function(){
					$("select.dropdown-group[id='"+id+"']").val(val_selected_old);
					$("select.dropdown-group[id='"+id+"']").blur();
					$("select.dropdown-active[id='"+id+"']").prop('disabled', true);
                    $("select.dropdown-group[id='"+id+"']").prop('disabled', true);
				    $("a.user-delete[id='"+id+"']").hide();
                    $(".user-change[id='"+id+"']").show();
                    $("tr.user-row[id='"+id+"']").css("color","#333333");
					$("#modal_change_group").modal("hide");
				});

			});

        });
       //end change user group


        function getValText(val)
        {
            if (val == 'Y')
                return "Да";

            if (val == 'N')
                return "Нет";

            if (val == 'admin')
                return "Админстратор";

            if (val == 'dev')
                return "Разработчик";

            if (val == 'user')
                return "Пользователь";

            return val;
        }
    });
    
    //Password generator
    $("#generate_pass").click(function(){
        var result       = '';
        var words        = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
        var max_position = words.length - 1;
            for( i = 0; i < 10; ++i ) {
                position = Math.floor ( Math.random() * max_position );
                result = result + words.substring(position, position + 1);
            }
       $("#inputPassword").val(result);
    });
    
    
    
    // create new user
	$("#create_user_btn").click(function(){
        $("#success_alert").html("");
        $("#success_alert").hide();
        $("#error_alert").html("");
        $("#error_alert").hide();
	   	$("#create_user_modal").modal("show");
     // при нажатом чекбоксе отправляем письмо юзеру, что ему был создан аккаунт с таким-то логином и таким-то паролем, при этом добавляем его в базу как "активного"
	   		
	});

    $("#ok_create_user").click(function(){
        var notify;

        if ($("#notify").is(":checked")) {
            notify = 1;
        } else {
            notify = 0;
        }

        $.post("<?= $this->config->site_url('ajax/createUser') ?>", {
            'email'  : $("#inputEmail").val(),
            'passwd' : $("#inputPassword").val(),
            'notify' : notify
        }, function(result){
            var answer = $.parseJSON(result);

            if(answer.resCode == '00') {
                $("#success_alert").html("Учетная запись успешно создана!");
                $("#error_alert").hide();
                $("#success_alert").show();
                setTimeout(function(){ self.location.reload(); }, 2000);
            } if(answer.resCode == '01') {
                $("#error_alert").html("Учетная запись с данным Email уже зарегистрирована!");
                $("#success_alert").hide();
                $("#error_alert").show();
            } if(answer.resCode == '04') {
                $("#error_alert").html("Неверно указан Email адрес!");
                $("#success_alert").hide();
                $("#error_alert").show();
            } if(answer.resCode == '07') {
                $("#error_alert").html("Пароль не может быть пустым!");
                $("#success_alert").hide();
                $("#error_alert").show();
            }
        });
    });

    // search
    $("#search").click(function(){
        var st = $("#search_input").val();

        if (st != '')
        {
            self.location = "/search/user/"+st;
        }
    });
    
</script>